<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px">
    <ContentWrap>
      <el-form :model="queryParams" ref="queryFormRef" label-width="auto" :inline="true">
        <el-form-item label="客户类型" prop="customerType">
          <el-select
            v-model="queryParams.customerType"
            placeholder="请选择客户类型"
            :clearable="true"
          >
            <el-option :key="1" label="私海客户" :value="1" />
            <el-option :key="2" label="公海客户" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入名称" :clearable="true" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-select v-model="queryParams.source" clearable placeholder="请选择来源" filterable>
            <el-option
              v-for="item in customerModuleField.immutableFields.get('source')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-select v-model="queryParams.grade" clearable placeholder="请选择等级" filterable>
            <el-option
              v-for="item in customerModuleField.immutableFields.get('grade')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="阶段" prop="stage">
          <el-select v-model="queryParams.stage" clearable placeholder="请选择阶段" filterable>
            <el-option
              v-for="item in customerModuleField.immutableFields.get('stage')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="queryParams.state" clearable placeholder="请选择状态" filterable>
            <el-option
              v-for="item in customerModuleField.immutableFields.get('state')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="拥有人" prop="ownerId">
          <el-select v-model="queryParams.ownerId" placeholder="请输入拥有人">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="queryParams.address" placeholder="请输入地址" :clearable="true" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleClickSearch">
            <Icon icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="handleClickReset">
            <Icon icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <div class="flex">
        <Table
          ref="tableRef"
          :columns="columns"
          :page-param="queryParams"
          :adaptive="true"
          :page-data="queryData"
          height-per="65"
          @page-change="getPage"
          @select="handleTableSelectChange"
          @select-all="handleTableSelectAll"
        >
          <template #mailAddress="{ row }">
            <span style="font-weight: bold"> {{ row.contact.name }}</span>
            <span>&lt;{{ row.mailAddress }}&gt;</span>
          </template>
        </Table>
        <el-scrollbar
          style="
            width: 300px;
            height: 430px;
            border: 1px solid #ebeef5;
            margin-left: 20px;
            margin-right: 20px;
          "
        >
          <div v-for="row in selectContactMail" :key="row.id" class="flex m-3">
            <div
              style="
                display: flex;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 250px;
              "
              class="mr-2"
            >
              <span style="font-weight: bold"> {{ row.contact.name }}</span>
              <span>&lt;{{ row.mailAddress }}&gt;</span>
            </div>
            <el-button
              style="width: 15px; margin-left: auto; margin-right: 20px"
              text
              size="small"
              @click="() => handleDeleteMail(row.id)"
            >
              <Icon icon="ep:delete" />
            </el-button>
          </div>
        </el-scrollbar>
      </div>
    </ContentWrap>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script name="CustomerContactMailSelect" lang="ts" setup>
import * as CustomerContactApi from '@/api/customer/customerContact'
import * as UserApi from '@/api/system/user/user'

import { SettingBusinessModuleEnum } from '@/utils/constants'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'

const tableRef = ref()
const dialogTitle = ref('选择收件人')
const dialogVisible = ref(false)
const queryFormRef = ref()
const selectContactMail = ref<any[]>([])
const selectContactMailId = ref<Number[]>([])
const customerModuleField = ref()
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const queryParams = ref({
  name: undefined,
  customerType: 1,
  source: undefined,
  grade: undefined,
  stage: undefined,
  state: undefined,
  ownerId: undefined,
  address: undefined
})
const queryData = ref()
const columns = [
  {
    type: 'selection',
    alignWhole: 'center'
  },
  {
    label: '邮件地址',
    prop: 'mailAddress',
    slot: 'mailAddress'
  },
  {
    label: '客户名称',
    prop: 'contact.customer.name'
  }
]
/** 打开弹窗 */
const open = async () => {
  // 获得用户列表
  userList.value = await UserApi.getOwnerUser()
  customerModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)

  dialogVisible.value = true
  selectContactMail.value = []
  selectContactMailId.value = []
  handleClickReset()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = () => {
  emit('success', selectContactMail.value)
  dialogVisible.value = false
}

/** 搜索按钮操作 */
const handleClickSearch = () => {
  getPage()
}

/** 重置按钮操作 */
const handleClickReset = () => {
  queryFormRef.value?.resetFields()
  handleClickSearch()
}

/** 处理响应事件  */
const getPage = async () => {
  queryData.value = await CustomerContactApi.pageQueryMail(queryParams.value)
  reselectContactMail()
}

const reselectContactMail = () => {
  setTimeout(() => {
    tableRef.value.getTableRef().data.forEach((row) => {
      if (selectContactMailId.value.includes(row.id)) {
        tableRef.value.getTableRef().toggleRowSelection(row, true)
      }
    })
  }, 10)
}

const handleTableSelectChange = (newSelection, row) => {
  let isSelect = false
  newSelection.forEach((selectRow) => {
    if (selectRow.id == row.id) {
      isSelect = true
    }
  })
  if (isSelect) {
    if (!selectContactMailId.value.includes(row.id)) {
      selectContactMail.value.push(row)
      selectContactMailId.value.push(row.id)
    }
  } else {
    let index = selectContactMailId.value.indexOf(row.id)
    if (index >= 0) {
      selectContactMail.value.splice(index, 1)
      selectContactMailId.value.splice(index, 1)
    }
  }
}

const handleTableSelectAll = (newSelection) => {
  if (newSelection.length == 0) {
    tableRef.value.getTableRef().data.forEach((row) => {
      if (selectContactMailId.value.includes(row.id)) {
        let index = selectContactMailId.value.indexOf(row.id)
        if (index >= 0) {
          selectContactMail.value.splice(index, 1)
          selectContactMailId.value.splice(index, 1)
        }
      }
    })
  } else {
    newSelection.forEach((row) => {
      if (!selectContactMailId.value.includes(row.id)) {
        selectContactMail.value.push(row)
        selectContactMailId.value.push(row.id)
      }
    })
  }
}

const handleDeleteMail = (id) => {
  tableRef.value.getTableRef().data.forEach((row) => {
    if (row.id == id) {
      tableRef.value.getTableRef().toggleRowSelection(row, false)
    }
  })
  const index = selectContactMailId.value.indexOf(id)
  if (index >= 0) {
    selectContactMail.value.splice(index, 1)
    selectContactMailId.value.splice(index, 1)
  }
}
</script>
